package com.zego.wawaji.ui.center.address;

import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.noble.library.basic.string.StringUtils;
import com.zego.wawaji.R;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.base.utils.ChineseFilter;
import com.zego.wawaji.base.utils.InputUtils;
import com.zego.wawaji.ui.base.BaseAppCompatActivity;
import com.zego.wawaji.ui.center.address.bean.Address;
import com.zego.wawaji.ui.center.address.bean.JsonBean;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * 我的地址：编辑
 * Created by Su on 2017/12/1.
 */
public class MyEditAddressAct extends BaseAppCompatActivity implements View.OnClickListener {
    private EditText eit_name, eit_phone, eit_detail;
    private TextView tvAddress;

    private String name, phone, provinceName, cityName, districtName, address, addr_detail;

    private Address data;      // 上个页面传回数据
    private boolean isAdd = true;  // 区分是修改还是添加

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_address_edit_act);
        initTitle();
        initJsonData();
        initView();
    }

    private void initView() {
        data = getIntent().getParcelableExtra("Address");
        if (data != null) isAdd = false;

        eit_name = (EditText) findViewById(R.id.eit_name);
        eit_phone = (EditText) findViewById(R.id.eit_phone);
        eit_detail = (EditText) findViewById(R.id.eit_detail);
        tvAddress = (TextView) findViewById(R.id.address);
        findViewById(R.id.address_view).setOnClickListener(this);

        if (isAdd) return;

        eit_name.setText(data.getReceiverName());
        eit_phone.setText(data.getTelephone());
        eit_detail.setText(data.getStreet());
        address = data.getProvince() + " " + data.getCity();
        tvAddress.setText(address);
        InputUtils.endCursor(eit_name);
    }

    private void initTitle() {
        setTitle("新增收货地址");
        setBackView();
        setTitleRight("保存", this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_right:
                if (check()) {
                    if (isAdd) {
                        ModuleMgr.getCenterMgr().reqAddAddress(name, phone, provinceName, cityName, districtName, addr_detail, response -> {
                            if (response.isOk())
                                finish();
                        });
                        return;
                    }
                    ModuleMgr.getCenterMgr().reqUpdataAddress(data.getId(), name, phone, provinceName, cityName, districtName, addr_detail, response -> {
                        if (response.isOk())
                            finish();
                    });
                }
                break;

            case R.id.address_view:
                InputUtils.forceClose(this);
                showPickerView();
                break;
        }
    }

    private boolean check() {
        name = StringUtils.noSpace(eit_name.getText().toString());
        if (TextUtils.isEmpty(name)) {
            PToast.showShort("请输入收货人姓名");
            return false;
        }

        phone = StringUtils.noSpace(eit_phone.getText().toString());
        if (TextUtils.isEmpty(phone) || !ChineseFilter.isPhoneNumber(phone)) {
            PToast.showShort("请输入正确格式手机号");
            return false;
        }

        if (TextUtils.isEmpty(address)) {
            PToast.showShort("请输入地址");
            return false;
        }

        addr_detail = StringUtils.noSpace(eit_detail.getText().toString());
        if (TextUtils.isEmpty(addr_detail)) {
            PToast.showShort("请输入街道地址");
            return false;
        }
        return true;
    }

    // ============================================ 地址选择弹框 =====================================
    private ArrayList<JsonBean> options1Items = new ArrayList<>();                  // 省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();         // 市
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>(); // 区
    private OptionsPickerView pvOptions;

    private void showPickerView() {// 弹出选择器
        pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            //返回的分别是三个级别的选中位置
            provinceName = options1Items.get(options1).getPickerViewText();
            cityName = options2Items.get(options1).get(options2);
            districtName = options3Items.get(options1).get(options2).get(options3);
            address = provinceName + cityName + districtName;
            tvAddress.setText(address);
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.GRAY)
                .setContentTextSize(20)
                .build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据
        String JsonData = getJson("province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            options2Items.add(CityList);
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    public String getJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
